<?php

namespace Jinxing\Admin\Http\Controllers;

use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Jinxing\Admin\Models\Admin;
use Illuminate\Support\Facades\Auth;
use Jinxing\Admin\Repositories\ConfigRepository;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = 'admin/admin/index/index';

    /**
     * Create a new controller instance.
     *
     */
    public function __construct()
    {
        $this->middleware('guest:admin')->except('logout');
        $this->redirectTo = config('admin.home_url') ?: $this->redirectTo;
    }

    /**
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\View\View
     * @throws \Illuminate\Validation\ValidationException
     */
    public function index(Request $request)
    {
        if ($request->isMethod('POST')) {
            return $this->login($request);
        }

        $config = ConfigRepository::instance()->findBy(['name' => 'login'], 'config');
        return view('admin::auth.login', ['public_key' => Arr::get($config, 'public_key')]);
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showLoginForm()
    {
        $config = ConfigRepository::instance()->findBy(['name' => 'login'], 'config');
        return view('admin::auth.login', ['public_key' => Arr::get($config, 'public_key')]);
    }

    protected function guard()
    {
        return Auth::guard('admin');
    }

    /**
     * Validate the user login request.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function validateLogin(Request $request)
    {
        $rules = [
            $this->username() => 'required|string',
            'password'        => 'required|string',
        ];
        if (session()->get('admin.login.error')) {
            $rules['captcha'] = 'required|captcha';
        }

        $request->validate($rules);
    }

    /**
     * @param Request $request
     *
     * @return mixed
     */
    public function attemptLogin(Request $request)
    {
        $config      = ConfigRepository::instance()->findBy(['name' => 'login'], 'config');
        $private_key = Arr::get($config, 'private_key');
        $password    = decrypt_password($request->input('password'), $private_key);
        // 允许用邮箱和账号名称登录
        $email = $request->input('email');
        $key   = strpos($email, '@') ? 'email' : 'name';
        if (Auth::guard('admin')->attempt([
            $key       => $email,
            'password' => $password,
            'status'   => admin::STATUS_ENABLES,
        ], $request->filled('remember'))) {
            session()->forget('admin.login.error');
            return true;
        }

        session(['admin.login.error' => 1]);
        return false;
    }

    /**
     * The user has been authenticated.
     *
     * @param \Illuminate\Http\Request $request
     * @param mixed                    $user
     *
     */
    protected function authenticated(Request $request, $user)
    {
        if ($user instanceof Admin) {
            $user->update([
                'last_login_time' => date('Y-m-d H:i:s'),
                'last_login_ip'   => get_ip(),
            ]);
        }
    }

    /**
     * Log the user out of the application.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \Exception
     */
    public function logout(Request $request)
    {
        // 删除缓存信息
        $uid = $this->guard()->user()->getAuthIdentifier();
        cache()->store('file')->delete('admin:menus:' . $uid);
        cache()->store('file')->delete('admin:users:menus:' . $uid);

        // 登录用户退出
        $this->guard()->logout();
        $request->session()->invalidate();

        return redirect(config('admin.login_url'));
    }
}
